<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ title }}</span>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="盘点单号" prop="takingCode">
              <el-input v-model="form.takingCode" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="盘点类型" prop="takingType">
              <el-select v-model="form.takingType" placeholder="请选择盘点类型">
                <el-option
                  v-for="dict in typeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="仓库" prop="warehouseId">
              <el-select v-model="form.warehouseId" placeholder="请选择仓库" @change="handleWarehouseChange">
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.warehouseId"
                  :label="item.warehouseName"
                  :value="item.warehouseId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="盘点日期" prop="checkDate">
              <el-date-picker
                v-model="form.checkDate"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否盲盘" prop="blindFlag">
              <el-radio-group v-model="form.blindFlag">
                <el-radio label="Y">是</el-radio>
                <el-radio label="N">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否冻结库存" prop="frozenFlag">
              <el-radio-group v-model="form.frozenFlag">
                <el-radio label="Y">是</el-radio>
                <el-radio label="N">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="盘点说明" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入盘点说明"></el-input>
        </el-form-item>
      </el-form>

      <div class="mb20">
        <el-divider content-position="left">盘点明细</el-divider>
        <!-- 删除添加明细和删除按钮 -->

        <el-table 
          :data="detailList" 
          height="300" 
          :row-style="{height: '50px'}"
          :cell-style="{padding: '8px 0'}"
          :header-cell-style="{padding: '8px 0', fontWeight: 'bold', backgroundColor: '#f5f7fa'}"
        >
          <el-table-column label="序号" type="index" width="50" align="center" />
          <el-table-column label="物料编码" prop="itemCode" min-width="120" />
          <el-table-column label="物料名称" prop="itemName" min-width="120" />
          <el-table-column label="规格型号" prop="specification" min-width="150" show-overflow-tooltip />
          <el-table-column label="单位" prop="unitName" width="80" />
          <el-table-column label="系统库存" prop="systemQuantity" width="100" v-if="form.blindFlag !== 'Y'">
            <template slot-scope="scope">
              <span>{{ scope.row.systemQuantity }}</span>
            </template>
          </el-table-column>
          <el-table-column label="实际库存" prop="actualQuantity" width="150">
            <template slot-scope="scope">
              <el-input-number 
                v-model="scope.row.actualQuantity" 
                :min="0" 
                :precision="2"
                size="medium"
                controls-position="right" 
                @change="calculateDifference(scope.$index)" 
                style="width: 130px;"
                class="inventory-input"
              />
            </template>
          </el-table-column>
          <el-table-column label="盘盈盘亏" prop="differenceQuantity" width="100" v-if="form.blindFlag !== 'Y'">
            <template slot-scope="scope">
              <span :class="scope.row.differenceQuantity > 0 ? 'text-danger' : (scope.row.differenceQuantity < 0 ? 'text-success' : '')">
                {{ scope.row.differenceQuantity }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" min-width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入备注" />
            </template>
          </el-table-column>
          <!-- 删除操作列 -->
        </el-table>
      </div>

      <div class="bottom-control">
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button type="success" @click="submitAndClose">提交并关闭</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getInventoryCheck, addInventoryCheck, updateInventoryCheck } from "@/api/inventory/check";

// 添加仓库API引用
import { listWarehouse } from "@/api/ck/warehouse";
// 添加物料API引用
import { listMaterialByWarehouse } from "@/api/ck/material";

export default {
  name: "StockTakingAdd",
  data() {
    return {
      // 页面标题
      title: "",
      // 是否为编辑模式
      isEdit: false,
      // 表单参数
      form: {
        takingId: undefined,
        takingCode: "",
        takingName: "",
        takingType: "1",
        warehouseId: undefined,
        checkDate: undefined,
        remark: "",
        details: [],
        blindFlag: "N", // 新增盲盘选项
        frozenFlag: "Y" // 新增冻结库存选项，默认为是
      },
      // 表单校验
      rules: {
        takingType: [
          { required: true, message: "盘点类型不能为空", trigger: "change" }
        ],
        warehouseId: [
          { required: true, message: "仓库不能为空", trigger: "change" }
        ],
        checkDate: [
          { required: true, message: "盘点日期不能为空", trigger: "change" }
        ]
      },
      // 盘点类型字典
      typeOptions: [
        { dictLabel: "全面盘点", dictValue: "1" },
        { dictLabel: "动态盘点", dictValue: "2" },
        { dictLabel: "周期盘点", dictValue: "3" }
      ],
      // 仓库选项
      warehouseOptions: [],
      // 物料选项
      materialOptions: [],
      // 明细列表
      detailList: []
    };
  },
  created() {
    // 获取路由参数
    const id = this.$route.query.id;
    if (id) {
      this.isEdit = true;
      this.title = "编辑盘点单";
      this.getDetail(id);
    } else {
      this.isEdit = false;
      this.title = "新增盘点单";
      this.form.takingCode = this.generateCheckCode();
    }
    
    // 获取仓库列表
    this.getWarehouseOptions();
  },
  methods: {
    /** 获取详情 */
    getDetail(id) {
      getInventoryCheck(id).then(response => {
        this.form = response.data.data;
        this.detailList = this.form.details || [];
      });
    },
    /** 生成盘点单号 */
    generateCheckCode() {
      const date = new Date();
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
      return `PD${year}${month}${day}${random}`;
    },
    /** 获取仓库选项 */
    getWarehouseOptions() {
      listWarehouse().then(response => {
        if (response && response.rows) {
          this.warehouseOptions = response.rows.map(item => {
            return {
              warehouseId: item.warehouse_id,
              warehouseName: item.warehouse_name
            };
          });
        } else if (response && Array.isArray(response)) {
          // 如果返回的是数组而不是带rows的对象
          this.warehouseOptions = response.map(item => {
            return {
              warehouseId: item.warehouse_id,
              warehouseName: item.warehouse_name
            };
          });
        } else {
          console.error("获取仓库列表失败，返回数据格式不正确:", response);
          this.$modal.msgError("获取仓库列表失败");
        }
      }).catch(error => {
        console.error("获取仓库列表错误:", error);
        this.$modal.msgError("获取仓库列表失败");
      });
    },
    /** 仓库选择变更 */
    handleWarehouseChange(warehouseId) {
      // 清空物料选项
      this.materialOptions = [];
      // 清空明细列表
      this.detailList = [];
      
      // 根据仓库ID获取该仓库的物料
      if (warehouseId) {
        listMaterialByWarehouse(warehouseId).then(response => {
          // 添加调试日志
          console.log("物料API返回数据:", response);

          // 处理返回数据
          let materialData = [];
          if (response && response.rows) {
            materialData = response.rows;
          } else if (response && Array.isArray(response)) {
            materialData = response;
          } else if (response && response.data && Array.isArray(response.data)) {
            materialData = response.data;
          } else {
            console.error("获取物料列表失败，返回数据格式不支持:", response);
            this.$modal.msgError("获取物料列表失败");
            return;
          }

          // 记录物料数据
          if (materialData.length > 0) {
            console.log("第一条物料数据:", materialData[0]);
            console.log("第一条物料数据的字段名:", Object.keys(materialData[0]));
          }
          
          this.materialOptions = materialData.map(item => {
            // 映射物料数据
            // 检查原始数据中所有字段名及值
            const allKeys = Object.keys(item);
            const specKeys = allKeys.filter(key => 
              key.toLowerCase().includes('spec') || 
              key.toLowerCase().includes('规格') || 
              key === 'spec' || key === 'specification'
            );
            
            // 尝试从多个字段获取规格信息
            let spec = '';
            for (const key of specKeys) {
              if (item[key]) {
                spec = item[key];
                console.log(`从字段 ${key} 获取到规格信息: ${spec}`);
                break;
              }
            }
            
            if (!spec) {
              console.log(`物料 ${item.item_name || item.material_name} 未找到规格信息，原始字段:`, allKeys);
            }
            
            return {
              itemId: item.item_id || item.material_id,
              itemCode: item.item_code || item.material_code || item.code || item.itemId,
              itemName: item.item_name || item.material_name,
              specification: spec || item.material_spec || item.specification || item.spec || "",
              unitName: item.unit_name || item.unit_of_measure || item.material_unit,
              systemQuantity: item.onhand_num || item.quantity_num || 0,
              unitPrice: item.unit_price || item.material_purchasePrice || 0
            };
          });
          
          // 将物料选项转换为明细列表
          this.materialOptions.forEach(material => {
            const newDetail = {
              resultId: undefined,
              takingId: this.form.takingId,
              itemId: material.itemId,
              itemCode: material.itemCode,
              itemName: material.itemName,
              specification: material.specification,
              unitName: material.unitName,
              systemQuantity: material.systemQuantity || 0,
              actualQuantity: material.systemQuantity || 0, // 确保有默认值
              differenceQuantity: 0,
              remark: "",
              editable: false
            };
            this.detailList.push(newDetail);
          });
          
          console.log("生成的明细列表:", this.detailList);
        }).catch(error => {
          console.error("获取物料列表错误:", error);
          this.$modal.msgError("获取物料列表失败");
        });
      }
    },
    /** 物料选择变更 */
    handleMaterialChange(materialId, index) {
      const material = this.materialOptions.find(item => item.itemId === materialId);
      if (material) {
        this.detailList[index].itemName = material.itemName;
        this.detailList[index].specification = material.specification;
        this.detailList[index].unitName = material.unitName;
        this.detailList[index].systemQuantity = material.systemQuantity;
        this.detailList[index].unitPrice = material.unitPrice;
        this.detailList[index].actualQuantity = material.systemQuantity; // 默认与系统库存相同
        this.detailList[index].differenceQuantity = 0; // 差异初始为0
        this.detailList[index].editable = false; // 选择后不再可编辑
      }
    },
    /** 计算差异 */
    calculateDifference(index) {
      const detail = this.detailList[index];
      // 如果是盲盘，不显示差异
      if (this.form.blindFlag === "Y") {
        return;
      }
      
      // 确保实际库存有值
      if (detail.actualQuantity === null || detail.actualQuantity === undefined) {
        detail.actualQuantity = detail.systemQuantity || 0;
      }
      
      if (detail.systemQuantity !== undefined && detail.actualQuantity !== undefined) {
        // 使用parseFloat确保进行数值计算而非字符串连接
        detail.differenceQuantity = parseFloat((detail.actualQuantity - detail.systemQuantity).toFixed(2));
        
        // 计算金额差异
        if (detail.unitPrice !== undefined) {
          detail.systemAmount = parseFloat((detail.systemQuantity * detail.unitPrice).toFixed(2));
          detail.actualAmount = parseFloat((detail.actualQuantity * detail.unitPrice).toFixed(2));
          detail.differenceAmount = parseFloat((detail.differenceQuantity * detail.unitPrice).toFixed(2));
        }
      }
    },
    /** 表单提交 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 检查明细
          if (this.detailList.length === 0) {
            this.$modal.msgError("请先选择仓库获取盘点明细");
            return;
          }
          
          // 检查明细数据完整性并确保所有行有actualQuantity值
          for (let i = 0; i < this.detailList.length; i++) {
            const detail = this.detailList[i];
            if (!detail.itemId) {
              this.$modal.msgError(`第${i+1}行明细数据不完整`);
              return;
            }
            
            // 如果actualQuantity未填写，则使用系统库存值
            if (detail.actualQuantity === undefined || detail.actualQuantity === null) {
              detail.actualQuantity = detail.systemQuantity || 0;
              // 计算差异
              this.calculateDifference(i);
            }
          }
          
          // 设置明细
          this.form.details = this.detailList;
          
          if (this.isEdit) {
            updateInventoryCheck(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.cancel();
            }).catch(error => {
              console.error("修改失败:", error);
            });
          } else {
            addInventoryCheck(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.cancel();
            }).catch(error => {
              console.error("新增失败:", error);
            });
          }
        }
      });
    },
    /** 提交并关闭 */
    submitAndClose() {
      this.submitForm();
    },
    /** 取消按钮 */
    cancel() {
      this.$router.push("/ck/Stocktaking");
    }
  }
};
</script>

<style scoped>
.bottom-control {
  margin-top: 20px;
  text-align: center;
}
.mb20 {
  margin-top: 20px;
  margin-bottom: 20px;
}
.mb8 {
  margin-bottom: 8px;
}
.text-danger {
  color: #F56C6C;
}
.text-success {
  color: #67C23A;
}
/* 修复input-number组件按钮被遮挡问题 */
::v-deep .el-input-number {
  width: 100%;
}
::v-deep .el-input-number .el-input__inner {
  padding-right: 30px;
  height: 32px;
  font-size: 14px;
}
::v-deep .el-input-number.is-controls-right .el-input__inner {
  padding-right: 50px;
}
::v-deep .el-input-number.is-controls-right .el-input-number__decrease,
::v-deep .el-input-number.is-controls-right .el-input-number__increase {
  height: 16px;
  line-height: 16px;
}
/* 调整表格行高 */
::v-deep .el-table__row {
  height: 50px !important;
}
::v-deep .el-table__body td {
  padding: 8px 0 !important;
}
::v-deep .el-table__header th {
  padding: 8px 0 !important;
  font-weight: bold;
}
/* 库存输入框样式 */
::v-deep .inventory-input .el-input-number__decrease, 
::v-deep .inventory-input .el-input-number__increase {
  width: 25px !important;
  height: 18px !important;
  line-height: 18px !important;
  font-size: 16px !important;
}
::v-deep .inventory-input .el-input__inner {
  font-size: 16px !important;
  height: 36px !important;
}
</style> 